<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="户籍地址" prop="userName">
        <el-input
          v-model="queryParams.userAddress"
          placeholder="请输入户籍地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="approved">
        <el-input
          v-model="queryParams.approved"
          placeholder="请输入审核状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年龄范围" prop="ageShow">
        <el-input
          v-model="ageShow"
          placeholder="请输入年龄范围，例如18-55"
          clearable
          @keyup.enter.native="handleQuery"
          @blur="validateSalaryRange"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['approve:subsidy:add']">新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['approve:subsidy:edit']">修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['approve:subsidy:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['approve:subsidy:export']" v-show="false">导出</el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="subsidyList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="身份证号" align="center" prop="idCard" />
      <el-table-column label="户籍地址" align="center" prop="issuingAuthority" />
      <el-table-column label="手机号" align="center" prop="userPhone" />
      <el-table-column label="性别" align="center" prop="sexCode">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_user_sex"
            :value="scope.row.sexCode"
          />
        </template>
      </el-table-column>
      <el-table-column label="民族" align="center" prop="nationCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.nation" :value="scope.row.nationCode" />
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="学历" align="center" prop="educationCode">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.education"
            :value="scope.row.educationCode"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="发证机关"
        align="center"
        prop="issuingAuthority"
      />
      <el-table-column label="提交时间" align="center" prop="createTime" />
      <el-table-column label="审核状态" align="center" prop="approved">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.approve_status"
            :value="scope.row.approved"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row)"
            >查看</el-button
          >
          <!-- v-hasPermi="['approve:subsidy:edit']" -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['approve:subsidy:remove']"
            >删除</el-button
          >
          <el-dropdown
            @command="(command) => handleCommand(command, scope.row)"
          >
            <span class="el-dropdown-link">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-coin"
                v-hasPermi="[
                  'approve:subsidy:approved',
                  'approve:subsidy:disApproved',
                  'approve:subsidy:unApproved',
                ]"
                >审核</el-button
              >
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="pass">
                <el-button
                  size="mini"
                  type="text"
                  v-hasPermi="['approve:subsidy:approved']"
                  >通过</el-button
                >
              </el-dropdown-item>
              <el-dropdown-item command="reject">
                <el-button
                  size="mini"
                  type="text"
                  v-hasPermi="['approve:subsidy:disApproved']"
                  >不通过</el-button
                >
              </el-dropdown-item>
              <el-dropdown-item command="reset">
                <el-button
                  size="mini"
                  type="text"
                  v-hasPermi="['approve:subsidy:unApproved']"
                  >重置</el-button
                >
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改外出务工补贴对话框 -->
    <el-dialog title="提交资料查看" :visible.sync="open" width="60%" append-to-body>
      <el-descriptions title="" :column="3" border>
        <!-- <el-descriptions-item label="姓名">{{
          formView.userName
        }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{
          formView.idCard
        }}</el-descriptions-item>
        <el-descriptions-item label="户籍地址">{{
          formView.issuingAuthority
        }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{
          formView.userPhone
        }}</el-descriptions-item>
        <el-descriptions-item label="性别">
        <template>
          <dict-tag
            :options="dict.type.sys_user_sex"
            :value="formView.sexCode"
          />
        </template>
      </el-descriptions-item>
        <el-descriptions-item label="民族">
        <template>
          <dict-tag :options="dict.type.nation" :value="formView.nationCode" />
        </template>  
      </el-descriptions-item>
        <el-descriptions-item label="年龄">{{
          formView.name
        }}</el-descriptions-item>
        <el-descriptions-item label="学历">{{
          formView.name
        }}</el-descriptions-item>
        <el-descriptions-item label="发证机关">{{
          formView.name
        }}</el-descriptions-item> -->
        <el-descriptions-item label="身份证照片（正面）">
          <ImagePreview :width='100' :src="formView.idCardPeople"></ImagePreview>
        </el-descriptions-item>
        <el-descriptions-item label="身份证照片（反面）">
          <ImagePreview :width="100" :src="formView.idCardEmblem"></ImagePreview>
        </el-descriptions-item>
        <el-descriptions-item label="社保卡照片">
          <ImagePreview :width="100" :src="formView.socialSecurityCard"></ImagePreview>
        </el-descriptions-item>

        <el-descriptions-item
          label="申请表"
          contentStyle="color: #61affe; cursor: pointer"
        >
        <el-tooltip class="item" effect="dark" content="点击下载" placement="top-start">
          <div @click="downloadFile(formView.applicationForm)">
            {{ formView.applicationFormName }}
          </div>
        </el-tooltip>
          
        </el-descriptions-item>
       
        <el-descriptions-item
          label="银行工资流水"
          contentStyle="color: #61affe; cursor: pointer"
        >
        
          <el-tooltip class="item" effect="dark" content="点击下载" placement="top-start">
            <div @click="downloadFile(formView.capitalFlow)">
            {{ formView.capitalFlowName }}
          </div>
        </el-tooltip>
        </el-descriptions-item>
        <el-descriptions-item
          label="务工合同"
          contentStyle="color: #61affe; cursor: pointer"
        >
         
          <el-tooltip class="item" effect="dark" content="点击下载" placement="top-start">
            <div @click="downloadFile(formView.laborContract)">
            {{ formView.laborContractName }}
          </div>
        </el-tooltip>
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button type="error" @click="open = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addSubsidy,
  checkApproved,
  checkDisApproved,
  checkUnApproved,
  delSubsidy,
  getSubsidy,
  listSubsidy,
  updateSubsidy,
} from "@/api/approve/subsidy";

export default {
  name: "Subsidy",
  dicts: ["approve_status", "sys_user_sex", "education", "nation"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 外出务工补贴表格数据
      subsidyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      ageShow: "",
      age: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        userAddress: null,
        params: {
          ageMin: null,
          ageMax: null,
        },
      },
      // 表单参数
      form: {},
      formView: {},
      // 表单校验
      rules: {
        id: [{ required: true, message: "$comment不能为空", trigger: "blur" }],
        workerId: [
          { required: true, message: "工人ID不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询外出务工补贴列表 */
    getList() {
      this.loading = true;
      listSubsidy(this.queryParams).then((response) => {
        this.subsidyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    extractFileNameFromUrl(url) {
      // 使用正则表达式或字符串操作来获取最后一个斜杠后的部分
      const fileName = url?.split('/').pop();
      
      // 返回文件名
      return fileName;
    },
    downloadFile(value) {
      const url = process.env.VUE_APP_BASE_API + value;
      // 下载
      const link = document.createElement("a");
      link.href = url;
      link.download = value || "download";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 年龄范围
    validateSalaryRange() {
      // 验证薪酬范围
      if (this.ageShow) {
        const [min, max] = this.ageShow.split("-").map(String);
        const range = [min, max];
        this.queryParams.params = {
          ageMin: min,
          ageMax: max,
        };
        if (range.length !== 2 || isNaN(range[0]) || isNaN(range[1])) {
          this.$message.error("请输入有效的年龄范围，例如18-55");
        } else {
          this.age = range;
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        workerId: null,
        subsidyContent: null,
        approved: null,
        approvedTime: null,
        approvedBy: null,
        unApprovedTime: null,
        unApprovedBy: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        ageShow: "",
        params: {
          ageMin: null,
          ageMax: null,
        },
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.ageShow = [];
      this.queryParams.params.ageMin = null;
      this.queryParams.params.ageMax = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加外出务工补贴";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      console.log("row", row);
      const id = row.id || this.ids;
      console.log("id", id);
      getSubsidy(id).then((response) => {
        const data = {
          ...response.data,
          laborContractName: this.extractFileNameFromUrl(response.data.laborContract),
          applicationFormName: this.extractFileNameFromUrl(response.data.applicationForm),
          capitalFlowName: this.extractFileNameFromUrl(response.data.capitalFlow),
        }
        this.formView = data;
        this.open = true;
        this.title = "修改外出务工补贴";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateSubsidy(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSubsidy(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除外出务工补贴编号为"' + ids + '"的数据项？')
        .then(function () {
          return delSubsidy(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "approve/subsidy/export",
        {
          ...this.queryParams,
        },
        `subsidy_${new Date().getTime()}.xlsx`
      );
    },

    // 审核
    handleCommand(command, row) {
      console.log("审核", command, row);
      switch (command) {
        case "pass":
          this.approve(row);
          break;
        case "reject":
          this.reject(row);
          break;
        case "reset":
          this.reset(row);
          break;
        default:
          break;
      }
    },

    approve(row) {
      checkApproved(row.id)
        .then((response) => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {});
    },
    reject(row) {
      checkDisApproved(row.id)
        .then((response) => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {});
    },
    reset(row) {
      checkUnApproved(row.id)
        .then((response) => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {});
    },
  },
};
</script>
